package server;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    private static final String SERVER_CONFIG_PATH = "conf/server.xml";
    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;
    private Mapper mapper = new Mapper();

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        // 加载 server.xml，初始化系统
        loadServerConfig();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
            threadPoolExecutor.execute(requestProcessor);
        }

    }

    /**
     * 读取并解析 /conf/server.xml
     * 创建 mapper ，生成并初始化 host, context容器 及 wrapper 对象
     */
    private void loadServerConfig() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(SERVER_CONFIG_PATH);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            // 读取 Host 配置
            List<Element> hostNodes = rootElement.selectNodes("//Server/Service/Engine/Host");
            for (Element hostNode : hostNodes) {
                // 实例化 Host ，并加入 Mapper 容器
                mapper.addHost(hostNode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("配置文件解析失败，系统中止启动");
            System.exit(0);
        }
    }
}
